<template>
  <div class="app-container">
    <!-- 搜索框部分 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="营业厅名称" prop="busName">
        <el-input v-model="queryParams.busName" @keyup.enter.native="handleQuery" placeholder="请输入营业厅名称" clearable />
      </el-form-item>
      <el-form-item label="营业厅位置" prop="busPosition">
        <el-input v-model="queryParams.busPosition" @keyup.enter.native="handleQuery" placeholder="请输入营业厅位置" clearable />
      </el-form-item>
      <el-form-item label="营业厅经度" prop="busLongitude">
        <el-input v-model="queryParams.busLongitude" @keyup.enter.native="handleQuery" placeholder="请输入营业厅经度" clearable />
      </el-form-item>
      <el-form-item label="营业厅纬度" prop="busLatitude">
        <el-input v-model="queryParams.busLatitude" @keyup.enter.native="handleQuery" placeholder="请输入营业厅纬度" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 按钮部分 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['wxassistant:wcbushallinfo:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['wxassistant:wcbushallinfo:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['wxassistant:wcbushallinfo:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['wxassistant:wcbushallinfo:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 信息部分 -->
    <el-table v-loading="loading" :data="wcBusHallInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="序号" type="index" width="50" align="center">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>


      <el-table-column label="营业厅名称" prop="busName" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="营业厅位置" prop="busPosition" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="营业厅经度" prop="busLongitude" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="营业厅纬度" prop="busLatitude" align="center" :show-overflow-tooltip="true" />
      <!-- <el-table-column label="备注" prop="remark" align="center" :show-overflow-tooltip="true"/> -->
      <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['wxassistant:wcbushallinfo:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['wxassistant:wcbushallinfo:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改营业厅信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">


        <el-form-item label="营业厅名称" prop="busName">
          <el-input v-model="form.busName" placeholder="请输入营业厅名称" />
        </el-form-item>

        <el-form-item label="位置选择" prop="busPosition">

          <el-button type="primary" size="mini" @click="map_one">点击选择位置</el-button>

        </el-form-item>
        <el-form-item label="营业厅位置" prop="busPosition" style="display: none;">
          <el-input v-model="form.busPosition" placeholder="请输入营业厅位置" />
        </el-form-item>
        <el-form-item label="营业厅经度" prop="busLongitude" style="display: none;">
          <el-input v-model="form.busLongitude" placeholder="请输入营业厅经度" />
        </el-form-item>
        <el-form-item label="营业厅纬度" prop="busLatitude" style="display: none;">
          <el-input v-model="form.busLatitude" placeholder="请输入营业厅纬度" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>



    <!-- 地图框 -->
    <el-dialog :title="title" :visible.sync="openone" height="400px" append-to-body>
      <div class="map_one">
        <h1>
          <map_one @updatePosition="updatePosition" :defaultPosition="defaultPosition"></map_one>
        </h1>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormone">确 定</el-button>
        <el-button @click="cancelone">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import request from '@/utils/request'
import map_one from '../components/map_one.vue';
import * as XLSX from 'xlsx';
export default {
  components: {
    map_one
  },
  name: "WcBusHallInfo",
  data() {
    return {
      // 默认经纬度信息
      defaultPosition: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 营业厅信息表格数据
      wcBusHallInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openone: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,

        busName: null,
        busPosition: null,
        busLongitude: null,
        busLatitude: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {

        busName: [
          { required: true, message: "营业厅名称不能为空", trigger: "blur" }
        ],

        busPosition: [
          { required: true, message: "请选择营业厅位置", trigger: "blur" }
        ],

      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    updatePosition(position) {
      // console.log(`经纬度: ${position.longitude},${position.latitude}`);
      // console.log(position.longitude, position.latitude, position.positionName);
      this.form.busLongitude = position.longitude;
      this.form.busLatitude = position.latitude;
      this.form.busPosition = position.positionName;


    },
    /** 查询营业厅信息列表 */
    getList() {
      this.loading = true;
      listWcBusHallInfo(this.queryParams).then(res => {
        // console.log(res, '查看详情');
        if (res['success']) {
          const dt = res['data'];
          this.total = dt['total'];
          this.wcBusHallInfoList = dt['records'];
        }
        this.loading = false;
      });
      setTimeout(()=>{
        this.loading = false;
      },2000)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancelone() {
      this.openone = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        busName: null,
        busPosition: null,
        busLongitude: null,
        busLatitude: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加营业厅信息";
      // 设置默认经纬度为null
      // this.defaultPosition = null;
      // this.defaultPosition = {
      //     longitude: 114.351642,//经度
      //     latitude: 34.801549,  //经纬度
      //   };
      this.defaultPosition = {
        longitude: null,//经度
        latitude: null,  //经纬度
      };

    },
    // 打开地图按钮
    map_one() {
      // this.reset();
      this.openone = true;
      this.title = "位置选择";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getWcBusHallInfo(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改营业厅信息";
        // 设置默认经纬度为当前行的经纬度
        this.defaultPosition = {
          longitude: this.form.busLongitude,//经度
          latitude: this.form.busLatitude,  //经纬度
        };
        // this.defaultPosition = Object.assign({}, this.defaultPosition, { longitude: this.form.busLongitude, latitude: this.form.busLatitude });
        // console.log(this.defaultPosition, '点击');
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          //console.log(valid, '我想看看这');
          if (this.form.id != null) {
            updateWcBusHallInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWcBusHallInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }

      });
    },
    submitFormone() {
      this.openone = false;
      //console.log('点击了确定按钮');
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除营业厅信息编号为"' + ids + '"的数据项？').then(function () {
        return delWcBusHallInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    // handleExport() {
    //   this.download('wxassistant/wcbus_hall_info/export', {
    //     ...this.queryParams
    //   }, `wcBusHallInfo_${new Date().getTime()}.xlsx`)
    // }
    handleExport() {
      if (this.ids.length > 0) {
        //console.log(this.ids, 'you选中的');
        this.exportExcel()
      } else {

        this.$message.warning('请选择要导出的数据！');
      }
    },
    exportExcel() {
      // 假设你有一个表格数据的数组
      const data = [["营业厅名称", "营业厅位置","营业厅经度","营业厅纬度"],]; // 根据您的需求，这里应该是您想要导出的列标题

      // 遍历this.ids，找到对应的记录，并添加到data中
      this.ids.forEach(id => {
        // 假设this.wcBusHallInfoList
        const record = this.wcBusHallInfoList.find(item => item.id === id);
        if (record) {
          // 添加记录到data数组中，根据您的需求，这里应该是记录的对应字段
          data.push([record.busName, record.busPosition,record.busLongitude,record.busLatitude]);
        }
      });

      // 如果没有选中任何记录，则返回
      if (data.length === 1) {
        this.$message.warning('请选择要导出的数据！');
        return;
      }

      // 将数据转换为工作表
      const ws = XLSX.utils.aoa_to_sheet(data);

      // 创建工作簿并添加工作表
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

      // 生成Excel文件
      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });

      // 字符串转ArrayBuffer
      function s2ab(s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
      }

      // 保存文件
      saveAs(new Blob([s2ab(wbout)], { type: 'application/octet-stream' }), `selected_wcRemindMonitor_${new Date().getTime()}.xlsx`);
    }
  }
};

/** js请求 调用 */

// 查询营业厅信息列表
export function listWcBusHallInfo(query) {
  return request({
    url: '/wxassistant/wcbus_hall_info/page',
    method: 'get',
    params: query
  })
}

// 查询营业厅信息详细
export function getWcBusHallInfo(id) {
  return request({
    url: '/wxassistant/wcbus_hall_info/queryById/' + id,
    method: 'get'
  })
}

// 新增营业厅信息
export function addWcBusHallInfo(data) {
  return request({
    url: '/wxassistant/wcbus_hall_info/add',
    method: 'post',
    data: data
  })
}

// 修改营业厅信息
export function updateWcBusHallInfo(data) {
  return request({
    url: '/wxassistant/wcbus_hall_info/edit',
    method: 'put',
    data: data
  })
}

// 删除营业厅信息
export function delWcBusHallInfo(id) {
  return request({
    url: '/wxassistant/wcbus_hall_info/delete/' + id,
    method: 'delete'
  })
}

</script>
